/**
 * 神州信息(2012)
 */
package net.abbp.report.designer.components.resume;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;

import net.abbp.core.util.StringUtils;
import net.abbp.report.context.ReportContext;
import net.abbp.report.export.PdfExporter;
import net.abbp.report.model.ReportModel;
import net.abbp.report.model.io.impl.ModelXmlIO;
import net.abbp.report.view.GridView;

import com.jidesoft.swing.CheckBoxList;
import com.reportgear.core.data.SalaryHelper;
import com.reportgear.core.data.model.SalaryDataObject;
import com.reportgear.report.core.api.idname.DefaultIdName;
import com.reportgear.report.core.api.idname.IdName;
import com.reportgear.report.model.calculator.CalculatorHelper;
import com.reportgear.report.print.PreviewPane;
import com.reportgear.report.print.Printer;
import com.reportgear.report.print.ReportPage;
import com.reportgear.report.print.ReportPageIterator;

/**
 * 履历表打印面板
 * 
 * @version 1.0
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since ABBP 1.0
 * 
 *        Date：2012-4-16
 */
public class PrintPane extends JPanel {
    // 列表模型
    private DefaultListModel idsModel;
    // 人员列表
    private CheckBoxList lstIds;
    // 预览页面
    private PreviewPane preview;
    // 模板模型
    private ReportModel model;
    // 当前模板Id
    private int currTemplateId;
    // 当前选择的Id
    private String currId;

    public PrintPane() {
        this.initComponents();

        // 在这里使用JaxbUtils，出现权限无权限的错误
    }

    /**
     * 初始化控件
     */
    private void initComponents() {
        this.setLayout(new BorderLayout());

        this.add(this.createToolbar(), BorderLayout.NORTH);

        idsModel = new DefaultListModel();

        lstIds = new CheckBoxList(idsModel);
        lstIds.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lstIds.setFixedCellHeight(24);
        lstIds.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() >= 2) {
                    IdName<String> selected = (IdName<String>) ((JList) evt.getSource()).getSelectedValue();
                    if (selected != null) {
                        currId = selected.getId();
                        printViewResumt(currId);
                    }
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub

            }
        });

        preview = new PreviewPane();
        JSplitPane mainPane = this.createSplitPane(new JScrollPane(lstIds), preview);
        this.add(mainPane, BorderLayout.CENTER);

        JPanel statusBar = new JPanel();
        statusBar.setPreferredSize(new Dimension(100, 24));
        statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
        this.add(statusBar, BorderLayout.SOUTH);
    }

    /**
     * 创建工具栏
     */
    private JComponent createToolbar() {
        JPanel toolbar = new JPanel();

        toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.X_AXIS));
        toolbar.add(Box.createHorizontalStrut(30));
        toolbar.add(new JLabel("选择模板:"));
        toolbar.add(Box.createHorizontalStrut(10));

        JComboBox templateList = new JComboBox();
        DefaultComboBoxModel cbxModel = new DefaultComboBoxModel();
        List<SalaryDataObject> tmpList = SalaryHelper.INSTANCE.loadResumeTemplateList1();

        for (SalaryDataObject sdo : tmpList) {
            cbxModel.addElement(new DefaultIdName<Integer>(sdo.getInt("id"), sdo.getString("name")));
        }
        templateList.setModel(cbxModel);
        templateList.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent evt) {
                JComboBox cbx = (JComboBox) evt.getSource();
                IdName<Integer> idname = (IdName<Integer>) cbx.getSelectedItem();

                String template = SalaryHelper.INSTANCE.loadResumeTemplate(idname.getId());
                model = (new ModelXmlIO()).read(template);
                printViewResumt(currId);
            }
        });

        // 获取当前模板
        currTemplateId = ((IdName<Integer>) templateList.getSelectedItem()).getId();

        Dimension size = new Dimension(240, 22);
        templateList.setMaximumSize(size);
        templateList.setSize(size);
        templateList.setPreferredSize(size);

        toolbar.add(templateList);
        toolbar.add(Box.createHorizontalStrut(20));
        // 打印组件
        JButton btnPrint = new JButton("打印勾选");
        toolbar.add(btnPrint);
        btnPrint.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent evt) {
                Object[] checkedList = lstIds.getCheckBoxListSelectedValues();
                List<String> ids = new ArrayList<String>();
                for (Object o : checkedList) {
                    @SuppressWarnings("unchecked")
                    IdName<String> currNode = (IdName<String>) o;

                    ids.add(currNode.getId());
                }

                printResume(ids.toArray(new String[0]));
            }
        });
        toolbar.add(Box.createHorizontalStrut(10));

        // 打印组件
        JButton btnExport = new JButton("导出勾选");
        toolbar.add(btnExport);
        btnExport.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent evt) {
                Object[] checkedList = lstIds.getCheckBoxListSelectedValues();
                List<String> ids = new ArrayList<String>();
                for (Object o : checkedList) {
                    @SuppressWarnings("unchecked")
                    IdName<String> currNode = (IdName<String>) o;

                    ids.add(currNode.getId());
                }

                exportResume2Pdf(ids.toArray(new String[0]));
            }
        });
        toolbar.add(Box.createHorizontalStrut(10));

        JButton btnPrintCurrent = new JButton("打印当前");
        btnPrintCurrent.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent evt) {
                @SuppressWarnings("unchecked")
                IdName<String> selected = (IdName<String>) lstIds.getSelectedValue();

                printResume(new String[] { selected.getId() });
            }
        });
        toolbar.add(btnPrintCurrent);

        toolbar.add(Box.createHorizontalGlue());

        return toolbar;
    }

    /**
     * 导出PDF
     * 
     * @param is 所有Id
     */
    protected void exportResume2Pdf(String[] ids) {
        JFileChooser fc = new JFileChooser();
        fc.setFileFilter(new FileNameExtensionFilter("PDF文件", "pdf"));
        fc.setDialogTitle("导出为PDF文件");
        // GridView gridView = ReportContext.INSTANCE.getCurrentView();
        // Window wnd = SwingUtilities.getWindowAncestor(gridView);
        if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            String fileName = fc.getSelectedFile().getAbsolutePath();

            if (!fileName.toLowerCase().endsWith(".pdf")) {
                fileName = fileName + ".pdf";
            }

            if (model == null) {
                String template = SalaryHelper.INSTANCE.loadResumeTemplate(currTemplateId);
                model = (new ModelXmlIO()).read(template);
            }

            List<ReportPage> pages = new ArrayList<ReportPage>();

            for (String id : ids) {
                ReportModel viewModel = CalculatorHelper.calResumeModel(model, id);
                Iterator<ReportPage> rs = new ReportPageIterator(viewModel);
                while (rs.hasNext()) {
                    pages.add(rs.next());
                }
            }
            new PdfExporter().exportPDF(pages, fileName);
        }
    }

    /**
     * 建立分隔面板
     * 
     * @param left
     *            左面板
     * @param right
     *            右面板
     * @return 分隔面板
     */
    private JSplitPane createSplitPane(Component left, Component right) {
        JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
        pane.setOneTouchExpandable(true);
        pane.setDividerLocation(200);

        return pane;
    }

    /**
     * 设置简历信息
     * 
     * @param resumeInfo
     *            简历信息
     */
    public void setResumeInfo(String resumeInfo) {
        if (!StringUtils.isEmpty(resumeInfo)) {
            String[] infos = resumeInfo.split(";");
            for (String info : infos) {
                String[] ids = info.split(",");

                this.idsModel.addElement(new DefaultIdName<String>(ids[0], ids[1]));
            }
        }
    }

    /**
     * 打印简历
     * 
     * @param ids
     *            简历Id列表
     */
    private void printResume(String[] ids) {
        if (model == null) {
            String template = SalaryHelper.INSTANCE.loadResumeTemplate(currTemplateId);
            model = (new ModelXmlIO()).read(template);
        }

        List<ReportPage> pages = new ArrayList<ReportPage>();

        for (String id : ids) {
            ReportModel viewModel = CalculatorHelper.calResumeModel(model, id);
            Iterator<ReportPage> rs = new ReportPageIterator(viewModel);
            while (rs.hasNext()) {
                pages.add(rs.next());
            }
        }

        new Printer().print(pages);
    }

    /**
     * 预览
     * 
     * @param id
     *            员工Id
     */
    private void printViewResumt(String id) {
        if (model == null) {
            String template = SalaryHelper.INSTANCE.loadResumeTemplate(currTemplateId);
            model = (new ModelXmlIO()).read(template);
        }

        ReportModel viewModel = CalculatorHelper.calResumeModel(model, id);

        preview.print(new ReportPageIterator(viewModel));
    }
}
